package chunk

import (
	"mig/pkg/digester"
	"mig/pkg/types"
)

type DigestV2Chunk struct {
	digesters []digester.Digester
	records   []*types.Record
	root      *types.DigestNode
}

func NewDigestV2Chunk() *DigestV2Chunk {
	return &DigestV2Chunk{}
}

func (c *DigestV2Chunk) Print() {
	for _, record := range c.records {
		record.Print()
	}
}

func (c *DigestV2Chunk) Digest() *types.DigestNode {
	return c.root
}

func (c *DigestV2Chunk) Records() []*types.Record {
	return c.records
}

func (c *DigestV2Chunk) AddRecord(record *types.Record) {
	c.records = append(c.records, record)
	n := record.Count()
	if c.digesters == nil {
		c.digesters = make([]digester.Digester, 0, n)
		for i := 0; i < n; i++ {
			c.digesters = append(c.digesters, digester.NewMD5Digester())
		}
	}
	for i, data := range record.ByteList() {
		c.digesters[i].Update(data)
	}
}

func (c *DigestV2Chunk) Finalize() {
	nodes := make([]*types.DigestNode, 0, len(c.digesters))
	for _, d := range c.digesters {
		nodes = append(nodes, &types.DigestNode{
			Digest: d.Finalize(),
		})
	}
	c.root = types.MergeDigestNodes(nodes, digester.NewMD5Digester())
}
